package com.jarvis.hospital.prescription;


import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.ImageDetailActivity;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.PatientChooseActivity;
import com.jarvis.hospital.patient.PatientManageFragment;
import com.jarvis.hospital.prescription.adapter.PrescriptionBloodAdapter;
import com.jarvis.hospital.prescription.adapter.PrescriptionDetailFragmentAdapter;
import com.jarvis.hospital.prescription.adapter.PrescriptionFragmentAdapter;
import com.jarvis.hospital.prescription.adapter.PrescriptionTimeAdapter;
import com.jarvis.hospital.prescription.model.AllPrescriptionModel;
import com.jarvis.hospital.prescription.model.BloodDetailModel;
import com.jarvis.hospital.prescription.model.BloodTimeModel;
import com.jarvis.hospital.prescription.model.CFIntervalListModel;
import com.jarvis.hospital.prescription.model.PrescriptionInfoDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionInfoModel;
import com.jarvis.hospital.prescription.model.PrescriptionTimeDetailModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;
import com.jarvis.hospital.widget.NoScrollViewPager;
import com.jarvis.hospital.widget.ScrollListView;
import com.jude.swipbackhelper.SwipeBackHelper;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class PrescriptionDetailActivity extends BaseActivity implements View.OnClickListener {

    private ApiService service;
    private String prescriptionId;
    private String programmeId;
    private PrescriptionInfoModel prescriptionInfoModel;

    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.lin_edit)
    LinearLayout lin_edit;
    @BindView(R.id.recy_blood)
    RecyclerView recy_blood;
    @BindView(R.id.recy_time)
    RecyclerView recy_time;
    private PrescriptionTimeAdapter prescriptionTimeAdapter;
    private PrescriptionBloodAdapter prescriptionBloodAdapter;


    @BindView(R.id.tv_patient_bed_no)
    TextView tv_patient_bed_no;
    @BindView(R.id.tv_patient_name)
    TextView tv_patient_name;
    @BindView(R.id.tv_patient_age)
    TextView tv_patient_age;
    @BindView(R.id.tv_patient_weight)
    TextView tv_patient_weight;
    @BindView(R.id.tv_patient_height)
    TextView tv_patient_height;
    @BindView(R.id.tv_MTXdose)
    TextView tv_MTXdose;
    @BindView(R.id.tv_MTXDuration)
    TextView tv_MTXDuration;
    @BindView(R.id.tv_CFdose)
    TextView tv_CFdose;
    @BindView(R.id.tv_CFInterval)
    TextView tv_CFInterval;
    @BindView(R.id.tv_blood)
    TextView tv_blood;
    @BindView(R.id.tv_patient_sex)
    TextView tv_patient_sex;
    @BindView(R.id.tv_patient_history)
    TextView tv_patient_history;
    @BindView(R.id.tv_edit)
    TextView tv_edit;
    @BindView(R.id.tv_review)
    TextView tv_review;
    @BindView(R.id.tv_startPrescriptionPlan)
    TextView tv_startPrescriptionPlan;
    @BindView(R.id.rel_coment)
    RelativeLayout rel_coment;
    private String h_start = "";
    private String m_start = "";
    private String start_date = "";
    private String start_time = "";
    private boolean isSelect_start;
    private Dialog dialog;
    private PrescriptionTimeAxisFragment prescriptionTimeAxisFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_prescription_detail;
    }

    @Override
    public void initData() {
        Bundle bundle = this.getIntent().getExtras();
        prescriptionId = bundle.getString("prescriptionId");
        programmeId = bundle.getString("programmeId");

        SwipeBackHelper.getCurrentPage(this).setDisallowInterceptTouchEvent(true);

        prescriptionTimeAdapter = new PrescriptionTimeAdapter(R.layout.item_prescription_time, new ArrayList<PrescriptionTimeDetailModel>());
        recy_time.setLayoutManager(new LinearLayoutManager(this));
        //recy_time.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        prescriptionTimeAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_time.setAdapter(prescriptionTimeAdapter);

        prescriptionBloodAdapter = new PrescriptionBloodAdapter(R.layout.item_prescription_blood, new ArrayList<BloodTimeModel>());
        recy_blood.setLayoutManager(new LinearLayoutManager(this));
        recy_blood.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        recy_blood.setAdapter(prescriptionBloodAdapter);
        loadData();
    }

    private void loadData() {
        showDialog("加载中");
        service.getPrescriptionInfo(prescriptionId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<PrescriptionInfoModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<PrescriptionInfoModel> prescriptionInfoModelResponseData) {
                        if (prescriptionInfoModelResponseData != null) {
                            int resultCode = prescriptionInfoModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                prescriptionInfoModel = prescriptionInfoModelResponseData.getData();
                                showData();
                            } else {
                                showTextToast(prescriptionInfoModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void showData() {
        PrescriptionInfoDetailModel prescriptionInfoDetailModel = prescriptionInfoModel.getPrescriptionInfo();
        tv_patient_bed_no.setText(prescriptionInfoDetailModel.getPatientBedNumber());
        tv_patient_name.setText(prescriptionInfoDetailModel.getPatientName());
        tv_patient_age.setText(prescriptionInfoDetailModel.getPatientAge());
        tv_patient_weight.setText(prescriptionInfoDetailModel.getPatientWeight());
        tv_patient_height.setText(prescriptionInfoDetailModel.getPatientHeight());
        tv_patient_history.setText(prescriptionInfoDetailModel.getPatientCondition());
        tv_MTXdose.setText(prescriptionInfoDetailModel.getMTXdose() + "mg");
        tv_MTXDuration.setText(prescriptionInfoDetailModel.getMTXTimeDuration() + "h");
        tv_CFdose.setText(prescriptionInfoDetailModel.getCFdose() + "mg");
        tv_CFInterval.setText(prescriptionInfoDetailModel.getCFTimeInterval() + "h");
        if ("0".equals(prescriptionInfoDetailModel.getPatientSexuality())) {
            tv_patient_sex.setText("女");
        } else {
            tv_patient_sex.setText("男");
        }
        List<BloodTimeModel> listBloodTime = prescriptionInfoModel.getListBloodTime();
        List<BloodTimeModel> bloodTimeShown=new ArrayList<>();
        String blood_inf = "";
        for (int i = 0; i < listBloodTime.size(); i++) {
            BloodTimeModel bloodTimeModel = listBloodTime.get(i);
            if ("1".equals(bloodTimeModel.getBloodIsSelect())) {
                bloodTimeShown.add(bloodTimeModel);
                if (TextUtils.isEmpty(blood_inf)) {
                    blood_inf = "给药起" + bloodTimeModel.getBloodInterval() + "h";
                } else {
                    blood_inf = blood_inf + ",给药起" + bloodTimeModel.getBloodInterval() + "h";
                }
            }
        }
        tv_blood.setText(blood_inf);

        BloodTimeModel bloodTimeModel = bloodTimeShown.get(0);
        if (TextUtils.isEmpty(bloodTimeModel.getAnalysisPic())) {
            recy_blood.setVisibility(View.GONE);
            tv_blood.setVisibility(View.VISIBLE);
        } else {
            recy_blood.setVisibility(View.VISIBLE);
            tv_blood.setVisibility(View.GONE);
        }
        prescriptionTimeAdapter.addData(prescriptionInfoModel.getListPrescriptionTimeAxis());
        prescriptionBloodAdapter.addData(bloodTimeShown);
        setViews();
    }

    private void setViews() {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userRole = userModel.getUserRole();
        Bundle bundle = this.getIntent().getExtras();
        int type = bundle.getInt("type");
        if (type == 1) {
            lin_edit.setVisibility(View.GONE);
            if ("dutynurse".equals(userRole)) {
                if (prescriptionInfoModel != null) {
                    PrescriptionInfoDetailModel prescriptionInfoDetailModel = prescriptionInfoModel.getPrescriptionInfo();
                    if ("0".equals(prescriptionInfoDetailModel.getIsStart())) {
                        tv_startPrescriptionPlan.setVisibility(View.VISIBLE);
                    } else {
                        tv_startPrescriptionPlan.setVisibility(View.GONE);
                    }
                } else {
                    tv_startPrescriptionPlan.setVisibility(View.GONE);
                }
            } else {
                tv_startPrescriptionPlan.setVisibility(View.GONE);
            }

        } else if (type == -1) {
            lin_edit.setVisibility(View.GONE);
            tv_startPrescriptionPlan.setVisibility(View.GONE);
        } else if (type == 0) {
            tv_startPrescriptionPlan.setVisibility(View.GONE);
            if ("doctor".equals(userRole)) {
                tv_review.setVisibility(View.GONE);
            } else if ("pharmacyPharmacist".equals(userRole)) {
                tv_edit.setVisibility(View.GONE);
            } else if ("clinicalPharmacist".equals(userRole)) {
                lin_edit.setVisibility(View.VISIBLE);
            } else {
                lin_edit.setVisibility(View.GONE);
            }
        } else if (type == 2) {
            tv_startPrescriptionPlan.setVisibility(View.GONE);
            tv_review.setVisibility(View.GONE);
            if ("doctor".equals(userRole)) {
                tv_edit.setVisibility(View.VISIBLE);
            } else if ("clinicalPharmacist".equals(userRole)) {
                tv_edit.setVisibility(View.VISIBLE);
            } else {
                tv_edit.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void initView() {
        service = RequestApi.create(ApiService.class);
        //setStatus(true);
        tv_title.setText("健康处方");
        rel_left.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        tv_review.setOnClickListener(this);
        rel_coment.setOnClickListener(this);
//        recy_time.setNestedScrollingEnabled(false);
//        recy_blood.setNestedScrollingEnabled(false);
        tv_startPrescriptionPlan.setOnClickListener(this);
        recy_blood.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                BloodTimeModel bloodDetailModel = prescriptionBloodAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.img_analysis:
                        Bundle bundle=new Bundle();
                        bundle.putString("url",bloodDetailModel.getAnalysisPic());
                        startActivity(ImageDetailActivity.class,bundle);
                        break;
                }
            }

            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }
        });
        setViews();
    }

    // 为了获取结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 2) {
            if (requestCode == 101) {
                finish();
            }
        }
    }

    private void reviewPrescriptionStatus(String type,String value) {
        showDialog("加载中");
        service.reviewPrescriptionStatus(prescriptionId, programmeId, type, value)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData allPrescriptionModelResponseData) {
                        if (allPrescriptionModelResponseData != null) {
                            int resultCode = allPrescriptionModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                finish();
                            } else {
                                showTextToast(allPrescriptionModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void startPrescriptionPlan() {
        showDialog("加载中");
        service.startPrescriptionPlan(prescriptionId, start_time)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData allPrescriptionModelResponseData) {
                        if (allPrescriptionModelResponseData != null) {
                            int resultCode = allPrescriptionModelResponseData.getResultCode();
                            showTextToast(allPrescriptionModelResponseData.getMessage());
                            if (resultCode == 200) {
                                finish();
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }
    private void showReviewDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_edit_review, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.show();
        TextView tv_back = (TextView) customView.findViewById(R.id.tv_back);
        TextView tv_pass = (TextView) customView.findViewById(R.id.tv_pass);
        final EditText ed_value = (EditText) customView.findViewById(R.id.ed_value);
        tv_pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                reviewPrescriptionStatus("1",value);
            }
        });
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                if(!TextUtils.isEmpty(value)){
                    reviewPrescriptionStatus("2",value);
                }else {
                    showTextToast("请输入审核意见");
                }
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_edit:
                Bundle bundle = new Bundle();
                bundle.putSerializable("prescriptionInfoModel", prescriptionInfoModel);
                bundle.putInt("type", 0);
                startActivityForResult(NewPrescriptionActivity.class, bundle, 101);
                break;
            case R.id.tv_startPrescriptionPlan:
                showStartDateDialog();
                break;
            case R.id.rel_left:
                finish();
                break;
            case R.id.rel_coment:
                Bundle bundle1=new Bundle();
                bundle1.putString("prescriptionId",prescriptionId);
                startActivity(CommentActivity.class,bundle1);
                break;
            case R.id.tv_review:
                showReviewDialog();
                break;
        }
    }

    public void showStartDateDialog() {
        Calendar d = Calendar.getInstance(Locale.CHINA);
        // 创建一个日历引用d，通过静态方法getInstance() 从指定时区 Locale.CHINA 获得一个日期实例
        Date myDate = new Date();
        // 创建一个Date实例
        d.setTime(myDate);
        // 设置日历的时间，把一个新建Date实例myDate传入
        int year = d.get(Calendar.YEAR);
        int month = d.get(Calendar.MONTH);
        int day = d.get(Calendar.DAY_OF_MONTH);
        //初始化默认日期year, month, day
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            /**
             * 点击确定后，在这个方法中获取年月日
             */
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                String m = "";
                if (monthOfYear + 1 < 10) {
                    m = "0" + (monthOfYear + 1);
                } else {
                    m = (monthOfYear + 1) + "";
                }

                String d = "";
                if (dayOfMonth < 10) {
                    d = "0" + dayOfMonth;
                } else {
                    d = dayOfMonth + "";
                }
                start_date = "" + year + "-" + m + "-" + d;
                showStartTimeDialog();
            }
        }, year, month, day);
        datePickerDialog.setMessage("请选择日期");
        datePickerDialog.show();
    }

    private void showStartTimeDialog() {

        Calendar calendar = Calendar.getInstance();
        final int hour = calendar.get(Calendar.HOUR_OF_DAY);
        final int minute = calendar.get(Calendar.MINUTE);

        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_time, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.setCancelable(false);
        dialog.show();
        TimePicker tp = (TimePicker) customView.findViewById(R.id.tp);
        TextView tv_yes = (TextView) customView.findViewById(R.id.tv_yes);
        tv_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelect_start) {
                    isSelect_start = false;
                } else {
                    start_time = start_date + " " + hour + ":" + minute + ":00";

                }
                System.out.println("start_time" + start_time);
                startPrescriptionPlan();
                dialog.dismiss();
            }
        });

        tp.setIs24HourView(true);
        tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                isSelect_start = true;
                if (hourOfDay < 10) {
                    h_start = "0" + hourOfDay;
                } else {
                    h_start = hourOfDay + "";
                }
                if (minute < 10) {
                    m_start = "0" + minute;
                } else {
                    m_start = minute + "";
                }
                start_time = start_date + " " + h_start + ":" + m_start + ":00";

            }
        });
    }
}
